<template>
  <view class="page-all">
    <Header :title="title" bgColor="#fff" :leftIconSize="20"></Header>
    <Tabs :list="list" :current="current" @changeTab="changeTab"></Tabs>
    <view class="search-content">
      <view class="left" v-if="selsetTabValue == '任务列表'">
        <uv-search placeholder="指标名称" bgColor="#fff" v-model="queryForm.targetName" @change="searchTarget"
                   :showAction="false"></uv-search>
      </view>
      <view class="left" v-else>
        <uv-search placeholder="学校名称" bgColor="#fff" v-model="queryForm.schoolName" :showAction="false"
                   @change="searchFun()" @clear="clearFun()" @blur="searchFun()"></uv-search>
      </view>

      <view class="screen-icon" @click="screen">
        <image v-if="iconFlag === true" src="@/static/image/index/icon2.png" mode="widthFix"></image>
        <image v-else src="@/static/image/index/icon1.png"  mode="widthFix"></image>
      </view>
    </view>
    <view class="list-container">
      <scroll-view scroll-y="true" refresher-enabled="true" :refresher-triggered="triggered" :lower-threshold="50"
                   :style="{height: `calc(100vh - 44px - 66px - ${TopHeight.top}px)`}" @scrolltolower="nextPage"
                   :refresher-threshold="80"
                   refresher-background="rgb(244, 244, 244)" @refresherpulling="onPulling" @refresherrefresh="onRefresh"
                   @refresherrestore="onRestore" @refresherabort="onAbort">

        <view v-if="selsetTabValue == '任务列表'">
          <uv-swipe-action>
            <view class="item swipe-action" v-for="(item, index) in dataList" :key="index">
              <uv-swipe-action-item :options="options" @click="deleteSwipe(item)" :disabled=" selsetTabValue == '任务列表' && (item.noticeFlag === '1' || new Date() >= new Date(item.taskBeginDate+' 00:00:00'))">
                <view style="padding:20px 20rpx 110rpx;display: flex">
                  <view class="img">
                    <image src="../../static/image/index/login.jpg"></image>
                    <view class="statu" :class="{ green: item.status === '1' }">
                      {{ item.status === '1' ? '已完成' : item.status === '0.5' ? '已超期未完成' :'未完成' }}
                    </view>
                  </view>
                  <view class="info">
                    <!-- 根据是否显示整改报告判断跳转展示不同的详情页面 -->
                    <view>
                      <view class="row">
                        <view class="title">指标名称:</view>
                        <view class="con">{{ item.targetName }}</view>
                      </view>
                      <view class="row">
                        <view class="title">检查日期:</view>
                        <view class="con">{{ item.taskBeginDate }}~{{ item.taskEndDate }}</view>
                      </view>
                      <view class="row">
                        <view class="title">学校数量:</view>
                        <view class="con">{{ item.schoolId.split(',').length }}所</view>
                      </view>
                    </view>
                    <view class="btn-row" v-if="item.finishFlag === '0'">
                      <button :disabled="item.noticeFlag === '1'" @click="noticeSchool(item)">通知学校</button>
                      <button @click="toCheck(item)">检查</button>
                      <button :disabled="item.noticeFlag === '1' || new Date() >= new Date(item.taskBeginDate+' 00:00:00')"
                              @click="updateTask(item)">编辑
                      </button>
                    </view>
                  </view>
                </view>
              </uv-swipe-action-item>
            </view>
          </uv-swipe-action>
        </view>
        <view v-if="selsetTabValue !== '任务列表'">
            <view class="item no-swipe-item" v-for="(item, index) in dataList" :key="index">
                <view class="img" @click="toInfo(item.id)">
                  <image :src="item.filePath"></image>
                  <view class="statu" :class="{ green: item.lawStatus=='40'}">
                    {{ item.lawStatus == '10' ? '待上传' : (item.lawStatus == '20' && item.rectifyStatus == '20') ? '待审核' : (item.lawStatus == '20' && item.rectifyStatus == '10') ? '待整改' : item.lawStatus == '30' ? '待复查' : '已完成' }}
                  </view>
                </view>
                <view class="info">
                  <view @click="toInfo(item.id)">
                    <view class="row">
                      <view class="title">学校名称:</view>
                      <view class="con">{{ item.schoolName }}</view>
                    </view>
                    <view class="row">
                      <view class="title">指标名称:</view>
                      <view class="con">{{ item.targetName }}</view>
                    </view>
                    <view class="row">
                      <view class="title">检查日期:</view>
                      <view class="con">{{ item.lawDate }}</view>
                    </view>
                    <view class="row sign">
                      <view class="title" style="width: 150rpx">检查人签名:</view>
                      <view class="con">
                        <image :src="item.superviseSign" mode="heightFix"></image>
                      </view>
                    </view>
                  </view>
                  <view class="btn-row no-swipe-btn" v-if="item.lawStatus=='10'">
                    <button @click="goToUpload(item)">上传记录单</button>
                    <button @click="exportBill(item)">导出记录单</button>
                  </view>
                  <view class="btn-row no-swipe-btn" v-if="item.lawStatus=='20' && item.rectifyStatus=='20'">
                    <button @click="goToExamine(item)">审核</button>
                  </view>
                  <view class="btn-row no-swipe-btn" v-if="item.lawStatus == '30'">
                    <button @click="goToReview(item)">复查</button>
                  </view>
                  <view class="btn-row no-swipe-btn"
                        v-if="item.lawStatus == '40'">
                    <button @click="getInspectionReport(item)">检查报告</button>
                    <button v-if="item.isShowRectificationReport" @click="getRectifyReport(item)">整改报告</button>
                  </view>
                </view>
            </view>
        </view>
        <view v-if="emptyFlag" class="empty-box">
          <uv-empty mode="data" icon="/static/image/no-data.png" width="200rpx" height="260rpx" text="&nbsp;"/>
        </view>
        <uv-gap height="136rpx"></uv-gap>
      </scroll-view>
    </view>

    <view class="check-bottom-box" @click.stop v-if="selsetTabValue == '任务列表'">
      <button class="sure-button" @click.stop="toCreate()">创建任务</button>
    </view>

    <!--筛选弹层-->
    <uv-popup ref="taskPopup" @change="taskChange" :closeable="true">
      <view class="popup-title">筛选</view>
      <view class="popup-content">
        <view class="popup-title-row">
          <text>状态</text>
        </view>
        <view class="popup-con-row">
          <view class="item" :class="{ actived: finishFlag == item.name }" v-for="(item, index) in finishList"
                :key="index" @click="chooseFinish(item)">
            {{ item.name }}
          </view>
        </view>
        <view class="popup-title-row">
          <text>检查日期</text>
        </view>
        <view class="popup-date-row">
          <view class="date" @click="showTaskCalendar()">{{ startDate }}</view>
          <view class="to">至</view>
          <view class="date" @click="showTaskCalendar()">{{ endDate }}</view>
          <uv-calendars ref="taskCalendar" reset-text="清空" @reset="dateReset" mode="range" @confirm="dateConfirm" allowSameDay="true"></uv-calendars>
        </view>
        <view class="bottom-box" @click.stop>
          <button class="yellow-sure-button" style="width: 49%" @click.stop="resetForm()">重置</button>
          <button class="sure-button" @click.stop="popupTaskSubmit()">确认</button>
        </view>
      </view>
    </uv-popup>
    <!--筛选弹层-->
    <uv-popup ref="popup" @change="changeIcon" :closeable="true">
      <view class="popup-title">筛选</view>
      <view class="popup-content">
        <view class="popup-title-row">
          <text>检查日期</text>
        </view>
        <view class="popup-date-row">
          <view class="date" @click="showCalendar()">{{ startDate }}</view>
          <view class="to">至</view>
          <view class="date" @click="showCalendar()">{{ endDate }}</view>
          <uv-calendars ref="calendar" mode="range" resetText="清空" @reset="dateReset" @confirm="dateConfirm" allowSameDay="true"></uv-calendars>
        </view>
        <view class="popup-title-row">
          <text>办学性质</text>
        </view>
        <view class="popup-con-row">
          <view class="item" :class="{actived:queryForm.lawDetail.schoolPropertiesCode==item.value}"
                v-for="(item,index) in natureList" :key="index"
                @click="queryForm.lawDetail.schoolPropertiesCode=
                queryForm.lawDetail.schoolPropertiesCode===item.value?'':item.value"
          >{{ item.name }}
          </view>
        </view>
        <view class="popup-title-row">
          <text>办学类型</text>
        </view>
        <view class="popup-con-row">
          <view class="item" :class="{ actived: queryForm.lawDetail.doSchoolTypeCode == item.value }"
                v-for="(item, index) in typeList"
                :key="index" @click="queryForm.lawDetail.doSchoolTypeCode=
                queryForm.lawDetail.doSchoolTypeCode===item.value?'':item.value">
            {{ item.name }}
          </view>
        </view>
        <view class="popup-title-row" v-if="areaList.length>0">
          <text>地区</text>
        </view>
        <view class="popup-con-row">
          <view v-for="(item,index) in areaList" :key="index" class="item"
                :class="{actived:item.code === area}" @click="areaFun(item)">
            {{ item.name }}
          </view>
        </view>
        <view class="bottom-box" @click.stop>
          <button class="yellow-sure-button" style="width: 49%" @click.stop="resetForm()">重置</button>
          <button class="sure-button" @click.stop="popupSubmit()">确认</button>
        </view>
      </view>
    </uv-popup>
  </view>
</template>

<script setup>
import {defineProps, getCurrentInstance, reactive, ref} from 'vue';

const {proxy} = getCurrentInstance();
import supTaskAPI from "@/api/law/supTask/supTask";
import supLawApi from "@/api/law/supLaw/supLaw";
import dictApi from "@/api/dict/dict";
import publicAPI from "@/api/law/public/public";
import {onLoad} from "@dcloudio/uni-app";
import TopHeight from "@/common/topHeight"
import dayjs from "dayjs";
import config from "@/common/config";
let imgMinioPath = ref(config.IMG_MINIO_PATH);
let iconFlag = ref(false);
const freshing = ref(false);
const triggered = ref(false);
const emptyFlag = ref(false);
const loadingType = ref('noMore');
const contentText = reactive({
  contentdown: "上拉显示更多",
  contentrefresh: "正在加载...",
  contentnomore: "没有更多数据了"
});
const userInfo = ref(uni.getStorageSync('userInfo'));
const title = ref("");
const props = defineProps({
  rectifyFlag: {
    type: String,
    default: null,
  }
});
const options = ref([{
  text: '删除',
  style: {
    backgroundColor: '#F53F3F',
    padding: '0 20px'
  }
}]);
const total = ref(0);
const queryForm = reactive({ // 查询条件
  pageSize: 10,
  pageNum: 1,
  createOrgId: userInfo.value.user.orgId,
  entryType:"",
  lawStatus: "10",
  lawType: "2",
  schoolName: '',
  params: {
    lawStartDate: '',
    lawEndDate: ''
  },
  lawDetail: {
    schoolPropertiesCode: null, //选中的学校性质
    doSchoolTypeCode: null,//选中的办学类型
  }
});

const keyword = ref('');
const cityCurren = ref('省直'); //选中城市
const natureCurren = ref('民办'); //选中的学校性质
const typeCurren = ref('小学');
const finishFlag = ref('');

// isShowRectificationReport是否显示整改报告
const dataList = reactive([]);
const typeList = ref([]);
const natureList = ref([]);

const finishList = ref([
  {name: '未完成', value: '0'},
  {name: '已超期未完成', value: '0.5'},
  {name: '已完成', value: '1'}
]);

onLoad((option) => {
  queryForm.entryType = option.entryType;
  uni.setStorageSync('entryType', queryForm.entryType);
  if (queryForm.entryType == '2') {
    title.value = '校园安全专项检查';
  } else if (queryForm.entryType == '7') {
    title.value = '有害生物专检';
  }
});

/** 筛选-地区 */
const area = ref('');
const areaList = ref([]);
let areaType = ref('');
// 获取地区列表
let getAreaList = async () => {
  let query = {};
  if (userInfo.value.user.org.county) { // 区
    areaType.value = '3';
    return;
  } else if (userInfo.value.user.org.city) { // 市
    areaType.value = '2';
    query.parentCode = userInfo.value.user.org.city;
  } else { // 省
    areaType.value = '1';
    query.parentCode = userInfo.value.user.org.province;
  }
  let res = await proxy.http.asyncPost(publicAPI.getAreaListByParentCode(query.parentCode));
  if (res.code === 0) {
    areaList.value = reactive(res.data);
  }
};
// 筛选选中
const areaFun = (item) => {
  if (area.value === item.code) {
    area.value = ''
  } else {
    area.value = item.code;
  }
};

let chooseFinish = (item) => {
  if(finishFlag.value === item.name) {
    finishFlag.value =''
    queryForm.status = ''
  }else {
    finishFlag.value = item.name;
    queryForm.status = item.value;
  }

}

let delTask = (item) => {
  console.log(item);
}

let searchTarget = () => {
  searchList()
}

let searchList = () => {
  queryForm.pageNum = 1;
  dataList.length = 0;
  if (selsetTabValue.value === '任务列表') {
    getsupTaskPage();
  } else {
    getLawPage();
  }
};

let getPage = () => {
  if (selsetTabValue.value === '任务列表') {
    getsupTaskPage();
  } else {
    getLawPage();
  }
};
/**删除*/
let deleteSwipe = (item) => {
  uni.showModal({
    title: '提示',
    content: '确定删除本条检查任务吗？',
    success: async (res) => {
      if (res.confirm) {
        let result = await proxy.http.asyncPost(supTaskAPI.delete(item.id));
        if (result.code === 0) {
          searchList();
          uni.showToast({title: "删除成功", icon: 'success'});
        } else {
          uni.showToast({title: result.msg, icon: 'none'});
        }
      }
    }, fail: (res) => {
    }
  });
};

//获取列表
let getsupTaskPage = async () => {
  let res = await proxy.http.asyncPost(supTaskAPI.getSupTaskPage, queryForm);
  if (res.code === 0) {
    total.value = res.data.total;
    if (queryForm.pageNum === 1) {
      dataList.length = 0;
    }
    dataList.push(...res.data.records);
    if (dataList.length < total.value) {
      loadingType.value = 'more';
    } else {
      loadingType.value = 'noMore'; //没有数据时显示‘没有更多’
    }
    emptyFlag.value = dataList.length <= 0;
  } else {
    await uni.showToast({title: res.msg, icon: 'none'});
  }
}

//获取列表
let getLawPage = async () => {
  let res = await proxy.http.asyncPost(supLawApi.getsupLawPage, queryForm);
  if (res.code === 0) {
    total.value = res.data.total;
    if (queryForm.pageNum === 1) {
      dataList.length = 0;
    }
    dataList.push(...res.data.records);
    if (dataList.length < total.value) {
      loadingType.value = 'more';
    } else {
      loadingType.value = 'noMore'; //没有数据时显示‘没有更多’
    }
    emptyFlag.value = dataList.length <= 0;
  } else {
    await uni.showToast({title: res.msg, icon: 'none'});
  }
}
//获取码表-学校性质
let getNatureList = async () => {
  let res = await proxy.http.asyncGet(dictApi.findDataListByType('school_properties'), {});
  if (res.code === 0) {
    natureList.value = [...res.data];
  }
}
//获取码表-办学类型
let getTypeList = async () => {
  let res = await proxy.http.asyncGet(dictApi.findDataListByType('do_school_type'), {});
  if (res.code === 0) {
    typeList.value = [...res.data];
  }
}

const list = ref([
  {
    name: '任务列表'
  },
  {
    id: 10,
    name: '待上传检查记录单'
  },
  {
    id: 20,
    name: '待审核'
  },
  {
    id: 30,
    name: '待复查'
  },
  {
    id: 40,
    name: '已完成'
  }
]);
const selsetTabValue = ref('任务列表');
const current = ref(0);

//点击tab切换
function changeTab(e) {
  iconFlag.value = false;
  finishFlag.value = '全部';
  selsetTabValue.value = e.name;
  startDate.value = '开始日期';
  endDate.value = '结束日期';
  queryForm.taskBeginDate = ''
  queryForm.taskEndDate = ''
  queryForm.finishFlag = ''
  queryForm.targetName = ''
  queryForm.lawDetail.schoolPropertiesCode = null
  queryForm.lawDetail.doSchoolTypeCode = null
  area.value = ''
  queryForm.lawStatus = e.id;
  current.value = e.index;
  searchList()
}

function noticeSchool(item) {
  uni.showModal({
    title: '温馨提示',
    content: '确定通知学校？',
    success: async function (res) {
      if (res.confirm) {
        item.noticeFlag = '1'
        await notice(item)
      }
    }
  })
}

let notice = async (item) => {
  let res = await proxy.http.asyncPost(supTaskAPI.updateSupTask, item);
  if (res.code === 0) {
    await uni.showToast({icon: 'success', title: '通知成功', duration: 2000});
    setTimeout(() => {
      searchList();
    }, 2000)
  } else {
    await uni.showToast({title: res.msg, icon: 'none'});
  }
};

function toCheck(item) {
  let now = new Date().setHours(0, 0, 0, 0)
  let taskBeginDate = new Date(item.taskBeginDate).setHours(0, 0, 0, 0)
  let taskEndDate = new Date(item.taskEndDate).setHours(0, 0, 0, 0)
  if (now >= taskBeginDate && now <= taskEndDate) {
    //跳转到选择学校
    uni.navigateTo({
      url: `/packageLawEnforcement/pages/taskStartCheck/selectSchool?data=${encodeURIComponent(JSON.stringify(item))}`,
      success: () => {
        uni.$once("refresh", () => {
          searchList();
        });
      }
    })
  } else {
    uni.showToast({
      icon: 'error',
      title: '不在检查时间段内！'
    })
    return;
  }
}

//跳转开始创建
function toCreate() {
  uni.navigateTo({
    url: '/packageLawEnforcement/pages/createTask/index',
    success: () => {
      uni.$once("refresh", () => {
        searchFun();
      });
    }
  });
}

function updateTask(e) {
  uni.navigateTo({
    url: '/packageLawEnforcement/pages/createTask/index?data=' + encodeURIComponent(JSON.stringify(e)) + '&editFlag=' + true,
    success: () => {
      uni.$once("refresh", () => {
        searchList();
      });
    }
  });
}

// 跳转上传检查记录单
function goToUpload(item) {
  let data = {
    id: item.id,
    schoolId: item.schoolId
  }
  uni.navigateTo({
    url: `/packageLawEnforcement/pages/uploadRecord/index?data=${encodeURIComponent(JSON.stringify(data))}`,
    success: () => {
      uni.$once("refresh", () => {
        searchFun();
      });
    }
  });
}

const taskStartDate = ref('开始日期');
const taskEndDate = ref('结束日期');

const taskCalendar = ref();


//弹出开始时间选择
function showTaskCalendar() {
  taskCalendar.value.open();
}

function taskDateConfirm(e) {
  taskStartDate.value = e.range.before;
  taskEndDate.value = e.range.after;
}

const startDate = ref('开始日期');
const endDate = ref('结束日期');
const calendar = ref();

//弹出开始时间选择
function showCalendar() {
  calendar.value.open();
}

//判断筛选按钮颜色
let changeIcon = () => {
  if (queryForm.taskBeginDate || queryForm.taskEndDate || queryForm.finishFlag || queryForm.params.lawStartDate || queryForm.params.lawEndDate || queryForm.rectifyStatus ||
      queryForm.lawDetail.schoolPropertiesCode || queryForm.lawDetail.doSchoolTypeCode ||  queryForm.lawDetail.countyId) {
    iconFlag.value = true;
  } else {
    iconFlag.value = false;
  }
}
//判断任务列表筛选按钮颜色
let taskChange = () => {
  if (queryForm.taskBeginDate || queryForm.taskEndDate || queryForm.status) {
    iconFlag.value = true;
  } else {
    iconFlag.value = false;
  }
}

function dateConfirm(e) {
  startDate.value = e.range.before;
  endDate.value = e.range.after;
}

let popup = ref();

//显示筛选弹层
function showScreen() {
  popup.value.open('bottom');
}

let taskPopup = ref();

function screen() {
  if (selsetTabValue.value == '任务列表') {
    showTaskScreen();
  } else {
    showScreen();
  }
}

//显示筛选弹层
function showTaskScreen() {
  taskPopup.value.open('bottom');
}

function popupTaskSubmit() {
  if (startDate.value !== '开始日期') {
    queryForm.taskBeginDate = startDate.value;
  } else {
    queryForm.taskBeginDate = '';
  }
  if (endDate.value !== '结束日期') {
    queryForm.taskEndDate = endDate.value;
  } else {
    queryForm.taskEndDate = '';
  }
  taskPopup.value.close();
  searchList();
}

function popupSubmit() {
  if (startDate.value !== '开始日期') {
    queryForm.params.lawStartDate = startDate.value;
  } else {
    queryForm.params.lawStartDate = '';
  }
  if (endDate.value !== '结束日期') {
    queryForm.params.lawEndDate = endDate.value;
  } else {
    queryForm.params.lawStartDate = '';
  }
  if (areaType.value === '1') {
    queryForm.lawDetail.cityId = area.value;
  } else {
    queryForm.lawDetail.countyId = area.value;
  }
  popup.value.close();
  searchList();
}

const data = ref({});

//跳转查看信息页面
function toInfo(id) {
  uni.navigateTo({
    url: '/packageLawEnforcement/pages/viewInfo/viewDetail?id=' + id
  });
}

// 审核
function goToExamine(item) {
  uni.navigateTo({
    url: '/packageLawEnforcement/pages/rectify/rectifyFormIndex?id=' + item.id,
    success: () => {
      uni.$once("refresh", () => {
        searchFun();
      });
    }
  });
}

// 复查
function goToReview(item) {
  uni.navigateTo({
    url: '/packageLawEnforcement/pages/review/index?id=' + item.id,
    success: () => {
      uni.$once("refresh", (index) => {
        searchFun();
      });
    }
  });
}

//点击重置按钮
function resetForm() {
  natureCurren.value = '';
  typeCurren.value = '';
  cityCurren.value = '';
  startDate.value = '开始日期';
  endDate.value = '结束日期';
  taskStartDate.value = '开始日期';
  taskEndDate.value = '结束日期';

  queryForm.targetName = ''
  queryForm.schoolName = ''
  queryForm.taskBeginDate = ''
  queryForm.taskEndDate = ''
  queryForm.params.lawEndDate = ''
  queryForm.params.lawStartDate = ''
  area.value = '';
  keyword.value = '';
  queryForm.lawDetail.schoolPropertiesCode = null;
  queryForm.lawDetail.doSchoolTypeCode = null;
  finishFlag.value = ''
  queryForm.status = ''
  iconFlag.value = false;

  queryForm.params.lawStartDate = '';
  queryForm.params.lawStartDate = '';
  if (areaType.value === '1') {
    queryForm.lawDetail.cityId = area.value;
  } else {
    queryForm.lawDetail.countyId = area.value;
  }
  searchList();
  popup.value.close();
  taskPopup.value.close();
}
function dateReset(){
  startDate.value = '开始日期';
  endDate.value = '结束日期';
  taskStartDate.value = '开始日期';
  taskEndDate.value = '结束日期';
}
// 检查报告
let getInspectionReport = async (item) => {
  uni.showLoading({title: '下载中', mask: true});
  let header = proxy.http.handleHeader('HEADER_JSON', '', false)
  uni.downloadFile({ //只能是GET请求
    url: supLawApi.downloadLawPdfById(item.id),//下载地址接口返回
    header: header,
    success: (res) => {
      //下载成功
      if (res.statusCode === 200) {
        //保存文件
        let tempFile = res.tempFilePath;
        //文件名称
        let fileName = dayjs(new Date()).format('YYYY.MM.DD') + item.schoolName + item.targetName;
        //保存成功之后 打开文件
        uni.getFileSystemManager().saveFile({
          tempFilePath: tempFile,
          filePath: wx.env.USER_DATA_PATH + '/' + fileName + '记录单.pdf',//自定义文件名
          success(red) {
            uni.showModal({
              title: '提示',
              content: '文件已保存：' + red.savedFilePath,
              cancelText: '我知道了',
              confirmText: '打开文件',
              success: function (res) {
                if (res.confirm) {
                  uni.openDocument({
                    filePath: red.savedFilePath,
                    showMenu: true,
                    success: (sus) => {
                      // 添加分享
                      uni.onShareAppMessage(function () {
                      });
                    }
                  })
                }
              }
            });
          }
        })
      }
      uni.hideLoading();
    },
    fail: (e) => {
      console.log(e, '文件下载失败')
      uni.showToast({
        title: '文件下载失败',
        icon: "error",
      })
      uni.hideLoading();
    }
  });

}

/** 导出记录单按钮 */
let exportBill = async (item) => {
  uni.showLoading({title: '下载中', mask: true});
  let header = proxy.http.handleHeader('HEADER_JSON', '', false)
  uni.downloadFile({ //只能是GET请求
    url: supLawApi.downloadLawRecordPdfById(item.id),//下载地址接口返回
    header: header,
    success: (res) => {
      //下载成功
      if (res.statusCode === 200) {
        //保存文件
        let tempFile = res.tempFilePath;
        //文件名称
        let fileName = dayjs(new Date()).format('YYYY.MM.DD') + item.schoolName + item.targetName;
        //保存成功之后 打开文件
        uni.getFileSystemManager().saveFile({
          tempFilePath: tempFile,
          filePath: wx.env.USER_DATA_PATH + '/' + fileName + '记录单.pdf',//自定义文件名
          success(red) {
            uni.showModal({
              title: '提示',
              content: '文件已保存：' + red.savedFilePath,
              cancelText: '我知道了',
              confirmText: '打开文件',
              success: function (res) {
                if (res.confirm) {
                  uni.openDocument({
                    filePath: red.savedFilePath,
                    showMenu: true,
                    success: (sus) => {
                      // 添加分享
                      uni.onShareAppMessage(function () {
                      });
                    }
                  })
                }
              }
            });
          }
        })
      }
      uni.hideLoading();
    },
    fail: (e) => {
      console.log(e, '文件下载失败')
      uni.showToast({
        title: '文件下载失败',
        icon: "error",
      })
      uni.hideLoading();
    }
  });
}
/** 导出记录单按钮 */
let getRectifyReport = async (id) => {
  uni.showLoading({title: '下载中', mask: true});
  let header = proxy.http.handleHeader('HEADER_JSON', '', false)
  uni.downloadFile({ //只能是GET请求
    url: supLawApi.downloadLawRectifyPdfById(id),//下载地址接口返回
    header: header,
    success: (res) => {
      //下载成功
      if (res.statusCode === 200) {
        //保存文件
        let tempFile = res.tempFilePath;
        //文件名称
        let fileName = dayjs(new Date()).format('YYYY.MM.DD') + item.schoolName + item.targetName;
        //保存成功之后 打开文件
        uni.getFileSystemManager().saveFile({
          tempFilePath: tempFile,
          filePath: wx.env.USER_DATA_PATH + '/' + fileName + ' 整改报告.pdf',//自定义文件名
          success(red) {
            uni.showModal({
              title: '提示',
              content: '文件已保存：' + red.savedFilePath,
              cancelText: '我知道了',
              confirmText: '打开文件',
              success: function (res) {
                if (res.confirm) {
                  uni.openDocument({
                    filePath: red.savedFilePath,
                    showMenu: true,
                    success: (sus) => {
                      // 添加分享
                      uni.onShareAppMessage(function () {
                      });
                    }
                  })
                }
              }
            });
          }
        })
      }
      uni.hideLoading();
    },
    fail: (e) => {
      console.log(e, '文件下载失败')
      uni.showToast({
        title: '文件下载失败',
        icon: "error",
      })
      uni.hideLoading();
    }
  });
}
/** 搜索 */
let searchFun = () => {
  queryForm.pageNum = 1;
  searchList();
};

/** 清空搜索 */
let clearFun = () => {
  searchFun();
}


/** 滚动视图区域 */
    // 翻页
let nextPage = () => {
      if (queryForm.pageNum * queryForm.pageSize < total.value) {
        queryForm.pageNum++;
        getPage()
      }
    }
// 下拉
let onPulling = () => {
  freshing.value = false;
  setTimeout(() => {
    triggered.value = true;
  }, 1000)
};
// 刷新
let onRefresh = () => {
  if (freshing.value) return;
  triggered.value = 'restore';
  setTimeout(() => {
    freshing.value = false;
    triggered.value = false;
  }, 1000)
  //获取数据的函数
  queryForm.pageNum = 1 // 记录数
  getPage()
};
let onRestore = () => {
  triggered.value = 'restore'; // 需要重置
};
let onAbort = () => {
  console.log("onAbort");
};

const schoolNatureFun = (val,item) => {
  if (val === item.value) {
    val = '';
  } else {
    val = item.value;
  }
};
//页面加载
onMounted(() => {
  // download();
  if (props.rectifyFlag == null) {
    selsetTabValue.value = '任务列表';
    current.value = 0
    searchList();
  } else {
    queryForm.lawStatus = 10;
    current.value = 1
    selsetTabValue.value = '待上传检查记录单';
    searchList();
  }

  getNatureList();
  getTypeList();
  getAreaList();
})


</script>

<style lang="scss" scoped>
.bottom-box {
  padding: 0;

  .sure-button {
    width: 49% !important;
  }
}
::v-deep .swipe-action {
  .uv-swipe-action-item{
    width: 100%;
  }
}
.list-container {
  .item {
    overflow: hidden;
    padding: 0;
  }
  .no-swipe-item {
    padding: 40rpx 20rpx 10rpx 20rpx!important;
  }
}
.no-swipe-btn{
  margin-top: 30rpx!important;
  position: unset!important;
  width: 250px!important;
  padding-right:20rpx!important;
}
</style>
